package com.httpClient.chapter1;

import com.sky.JULLog.MyJulLogger;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

/**
 * @author : wushikai
 *         date : 2024-06-17
 */
public class ParamHttpClient {


    private static Logger log = MyJulLogger.getLogger(ParamHttpClient.class);


    public static void main(String[] args) throws Exception {
        doRequest();
    }


    private static void doRequest( ) throws IOException {


        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
        httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        HttpGet httpget = new HttpGet("http://localhost:8080/xy/expose/merDetail");
        httpget.setConfig(RequestConfig.custom().setSocketTimeout(10 * 1000).setConnectTimeout(10 * 1000).build());
        httpget.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        httpget.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
        httpclient.addRequestInterceptor((request, context) -> {
            log.info("" + request.getParams().getParameter(CoreProtocolPNames.PROTOCOL_VERSION));
            log.info("" + request.getParams().getParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET));
            log.info("" + request.getParams().getParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE));
            log.info("" + request.getParams().getParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING));
        });
        httpclient.getParams().setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 128 * 1024);

        HttpResponse response = httpclient.execute(httpget);

        handleResponse(response);


    }


    /**
     * 使用最简单的 流式读取
     */
    private static void handleResponse(HttpResponse response) throws IOException {

        log.info("response 的实现类是==>" + response.getClass().getCanonicalName());
        log.info("协议版本:" + response.getProtocolVersion());
        log.info("服务器返回状态码:" + response.getStatusLine().getStatusCode());
        log.info("服务器返回状态码表述:" + response.getStatusLine().getReasonPhrase());
        log.info("服务器返回状态描述:" + response.getStatusLine().toString());

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            log.warning("响应结果不是200, 直接返回");
            return;
        }


        //使用 响应头 获取 cookie 键值对,  注意这是没有被解析过的
        Header h1 = response.getFirstHeader("Set-Cookie");
        log.info("" + h1);  //mark 不知道为什么这是空的


        //使用 迭代器 获取 cookie 键值对 ,  httpClient 帮你解析好;
        HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator("Set-Cookie"));
        while (it.hasNext()) {
            HeaderElement elem = it.nextElement();
            log.info(elem.getName() + " = " + elem.getValue());
            NameValuePair[] params = elem.getParameters();
            for (NameValuePair param : params) {
                log.info(" " + param);
            }
        }


        HttpEntity entity = response.getEntity();   // 返回一个 HttpResponse 的 entity(实体) 这个  实体 = 响应头+响应内容

        if (entity != null) {
            InputStream inputStream = entity.getContent();   //实体对象 获取流 , 解析data 即可;
            byte[] buffer = new byte[2048];
            while (inputStream.read(buffer) != -1) {
                log.info("第一次读取的内容是:" + new String(buffer, StandardCharsets.UTF_8));
            }
            System.out.println();
            System.out.println("data  read  finished.......");
            inputStream.close();

        }


    }

}


